<?php
/**
 * Copyright (c) [2019] [吴跃忠]
 * [selibra] is licensed under the Mulan PSL v1.
 * You can use this software according to the terms and conditions of the Mulan PSL v1.
 * You may obtain a copy of Mulan PSL v1 at:
 * http://license.coscl.org.cn/MulanPSL
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
 * PURPOSE.
 * See the Mulan PSL v1 for more details.
 */

namespace ckeeper\utils;


use Selibra\Model\EntityProxy;

class EntityUtil
{

    /**
     * 该方法仅用于将实体类转换成数组，返回到前端的数据必须要再经过一遍过滤，不得直接将数数据原封直接返回到前端
     * @param array $entities
     * @param \Closure|null $closure
     * @param null $arrayKey
     * @return array
     */
    public static function eachArray(array $entities, \Closure $closure = null, $arrayKey = null)
    {
        $result = [];
        foreach ($entities as $key => $entity) {
            $data = EntityProxy::entityConversionToArray($entity);
            if (!empty($arrayKey)) {
                $key = $data[$arrayKey];
            }
            if (!is_null($closure)) {
                $result[$key] = $closure($data);
            } else {
                $result[$key] = $data;
            }
        }
        return $result;
    }


    /**
     * 数组数据转Entity对象
     * @param array $data 数组数据
     * @param object $entity $entity
     * @return mixed
     */
    public static function arrayDataToEntity(array $data, object &$entity): mixed
    {
        // 通过模型内的代理类转成对象
        $entityProxy = new EntityProxy($entity);
        $entityProxy->writeData($data);
        $entity = $entityProxy->getEntity();
        return $entity;
    }

}
